<script setup lang="ts">
import { reactive,onMounted, ref } from 'vue'
import { add_user,get_user_list } from '@/axios/api/acl/adduser'
import { ElNotification } from 'element-plus';

let user_list: any =reactive({
    userlist:[]
})
onMounted(() => {
    get_user_list().then(res => {
        if (res.code === 200) {
            user_list.userlist = JSON.parse(res.data)
        } else {
            ElNotification({
                title: '获取用户列表失败',
                message: res.msg,
                type: 'error'
            })
        }
    })
})


const form = reactive({
    UserNumber: '',
    UserName: '',
})

const UserNumber = (_rule: any, value: any, callback: any) => {
        // 判断value是否在tableData中
        let flag = false;
        user_list.userlist.forEach((item: any) => {
            if (item.UserNumber.toLowerCase() === value.toLowerCase()) {
                flag = true;
                return;
            }
        });

        if (flag) {
            callback(new Error('用户账号已存在'))
        } else {
            callback() //通过
        }
    }
const UserName = (_rule: any, value: any, callback: any) => {
    if (value.trim() === '') {
        callback(new Error('用户姓名不能为空'))
    } else {
        callback() //通过
    }
}

const rules = {
    UserNumber: [
            { validator: UserNumber, trigger: 'change' }
        ],
    UserName: [
            { validator: UserName, trigger: 'change' }
        ]
    }
let formRef: any = ref() // 新增抽屉表单对象

async function handleaddUser() {
    await formRef.value.validate();
    const res = await add_user(form)
    if (res.code === 200) {
        user_list.userlist.push(form.UserNumber)
        ElNotification({
            title: '成功',
            message: '添加用户成功',
            type:'success'
        })
    } else {
        ElNotification({
            title: '添加用户失败',
            message: res.msg,
            type: 'error'
        })
    }
}
</script>

<template>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户账号" prop="UserNumber">
            <el-input v-model="form.UserNumber" placeholder="请输入用户账号"></el-input>
        </el-form-item>
        <el-form-item label="用户姓名" prop="UserName">
            <el-input v-model="form.UserName" placeholder="请输入用户姓名"></el-input>
        </el-form-item>
        <el-form-item>
            <el-popconfirm width="220" confirm-button-text="OK" cancel-button-text="No, Thanks" icon="InfoFilled"
                    icon-color="#626AEF" title="是否确认添加用户?" @confirm="handleaddUser">
                    <template #reference>
                        <el-button type="primary">添加用户</el-button>
                    </template>
                </el-popconfirm>
        </el-form-item>
    </el-form>
</template>

<style lang="css" scoped>

</style>